﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace Labthink.PCSoft.UniversalHost4.Utility
{
    /// <summary>
    /// 密码hash+salt算法
    /// </summary>
    public class PasswordHash
    {
        /// <summary>
        /// 获取加盐后的hash值
        /// </summary>
        /// <param name="password"></param>
        /// <param name="salt"></param>
        /// <returns></returns>
        public static string HashPassword(string password, string salt)
        {
            return Md5Salt(password, salt);
        }

        /// <summary>
        /// 验证密码是否正确
        /// </summary>
        /// <param name="password"></param>
        /// <param name="salt"></param>
        /// <param name="correctHash"></param>
        /// <returns></returns>
        public static bool ValidatePassword(string password, string salt, string correctHash)
        {
            var testHash = HashPassword(password, salt);
            return string.Equals(testHash, correctHash);
        }

        /// <summary>
        /// 简单的加盐算法
        /// </summary>
        /// <param name="password"></param>
        /// <param name="salt"></param>
        /// <returns></returns>
        private static string Md5Salt(string password, string salt)
        {
            using var md5Provider = new MD5CryptoServiceProvider();
            var bytes = Encoding.UTF8.GetBytes(password + salt);
            var hash = md5Provider.ComputeHash(bytes);

            return Convert.ToBase64String(hash);
        }

        private static string Join(string password, string salt)
        {
            var os = (password + salt).ToCharArray();
            var ns = new char[os.Length];
            for (int i = 0; i < os.Length; i++)
            {
                if (i % 2 == 0)
                {
                    ns[i] = os[os.Length - 1 - i];
                }
                else
                {
                    ns[i] = os[i];
                }
            }
            return new string(ns);
        }
    }
}
